#include "StdAfx.h"
#include "download_file_thread.h"

download_file_thread::download_file_thread(void)
{
	this->ptr_http_client_ = NULL;
}

download_file_thread::~download_file_thread(void)
{
	if ( this->ptr_http_client_ )
	{
		delete this->ptr_http_client_;
		this->ptr_http_client_ = NULL;
	}
}

void 
download_file_thread::ActualWorkerThreadProc(PWORKER_PARAMETER work_para)
{
	aot::tt::ievent_base* ptr_notify = this->session_setting_.ptr_notify;
	_AFT::isession* ptr_session = this->session_setting_.ptr_session;

	if ( NULL == this->ptr_http_client_ )
	{
		this->ptr_http_client_ = new http_client;/// handled del
	}
	
	int result = -1;

	if ( ptr_session->get_type() == _AFT::isession::e_direct_download_file )
	{
		result = ptr_http_client_->download_file(this->session_setting_, FALSE);
	}	
	else if ( ptr_session->get_type() == _AFT::isession::e_download_file_with_check )
	{
		result = ptr_http_client_->download_file(this->session_setting_, TRUE);
	}
	else if ( ptr_session->get_type() == _AFT::isession::e_submit_check_without_download )
	{
		result = ptr_http_client_->check_file_download(this->session_setting_);
	}

	ptr_session->set_result(result);

	if ( ptr_notify )
	{
		ptr_notify->on_notify(WM_GLB_FTC_TO_UI_FINISH, (WPARAM)ptr_session, NULL);
	}
}

BOOL 
download_file_thread::DestroyThreads()
{
	if ( this->ptr_http_client_ )
	{
		this->ptr_http_client_->set_cancel();
	}

	WorkerThreads::DestroyThreads();

	if ( this->ptr_http_client_ )
	{
		this->ptr_http_client_->set_cancel(FALSE);
	}
	
	return TRUE;
}

void 
download_file_thread::config_session(_AFT::isession* ptr_session, aot::tt::ievent_base* ptr_notify)
{
	this->session_setting_.ptr_session = ptr_session; 
	this->session_setting_.ptr_notify = ptr_notify;
}

/// basic check by fan05